package com.tbit.uqbike.client.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tbit.uqbike.client.pojo.WeixinPayConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.net.ssl.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * SSL访问
 *
 * @author Leon
 * 2014-7-15 下午03:45:59
 */
public class MyX509TrustManager implements X509TrustManager {
    private final static Logger log = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

    X509TrustManager sunJSSEX509TrustManager;

    MyX509TrustManager() throws Exception {
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(MyX509TrustManager.class.getResourceAsStream("/ssc.keystore"), "123456".toCharArray());
        TrustManagerFactory tmf =
                TrustManagerFactory.getInstance("SunX509", "SunJSSE");
        tmf.init(ks);
        TrustManager tms[] = tmf.getTrustManagers();
        for (int i = 0; i < tms.length; i++) {
            if (tms[i] instanceof X509TrustManager) {
                sunJSSEX509TrustManager = (X509TrustManager) tms[i];
                return;
            }
        }
        throw new Exception("Couldn't initialize");
    }

    /**
     * 获取openId
     */
    public static String getOpenId(String code, WeixinPayConfig weixinPayConfig) {
        String openid = null;
        try {
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL myURL = new URL("https://api.weixin.qq.com/sns/jscode2session?appid=" + weixinPayConfig.getAppId() + "&secret=" + weixinPayConfig.getSecret() + "&js_code=" + code + "&grant_type=authorization_code");
            HttpsURLConnection httpsConn = (HttpsURLConnection) myURL.openConnection();
            httpsConn.setConnectTimeout(3000);
            httpsConn.setReadTimeout(3000);
            httpsConn.setSSLSocketFactory(ssf);
            InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
            StringBuffer result = new StringBuffer();
            int respInt = insr.read();
            while (respInt != -1) {
                result.append((char) respInt);
                respInt = insr.read();
            }
            JSONObject object = JSON.parseObject(result.toString());
            if (object.getString("errcode") == null) {
                openid = object.getString("openid");
            } else {
                log.warn(weixinPayConfig.getAppId()+"获取openId:" + result.toString());
            }
        } catch (Exception e) {
            log.error("获取openId异常", e);
        }

        return openid;
    }

    /**
     * 获取sessionKey
     */
    public static String getSessionKey(String code, String appId, String secret, StringBuffer stringBuffer) {
        String sessionKey = null;
        HttpsURLConnection httpsConn = null;
        try {
            String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                    appId, secret, code);

            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL myURL = new URL(url);
            httpsConn = (HttpsURLConnection) myURL.openConnection();
            httpsConn.setConnectTimeout(3000);
            httpsConn.setReadTimeout(3000);
            httpsConn.setSSLSocketFactory(ssf);
            InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
            StringBuffer result = new StringBuffer();
            int respInt = insr.read();
            while (respInt != -1) {
                result.append((char) respInt);
                respInt = insr.read();
            }
            //LogUtil.info(result.toString());
            JSONObject object = JSON.parseObject(result.toString());
            if (object.getString("errcode") == null) {
                sessionKey = object.getString("session_key");
                stringBuffer.append(object.getString("openid"));
            } else {
                log.warn("获取session_key失败:" + result.toString());
            }
        } catch (Exception e) {
            log.error("获取sessionKey异常", e);
        } finally {
            if (httpsConn != null) {
                httpsConn.disconnect();
            }
        }

        return sessionKey;
    }

    public static void main(String[] args) {
        // 连接超时(豪秒)
        int connectTimeout = 3000;
        // 接收数据超时(豪秒)
        int receiveTimeout = 3000;
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) new URL("http://192.168.1.110:8080/uqbike_client_youqu_war_exploded").openConnection();
            connection.setConnectTimeout(connectTimeout);
            connection.setReadTimeout(receiveTimeout);
            connection.connect();
            if (HttpURLConnection.HTTP_OK != connection.getResponseCode()) {
                System.out.println("地址不可用");
            }
            System.out.println("------------" + connection.getResponseCode());
        } catch (IOException e) {
            System.out.println("地址请求或响应超时");
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        try {
            sunJSSEX509TrustManager.checkClientTrusted(chain, authType);
        } catch (CertificateException excep) {
        }
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        try {
            sunJSSEX509TrustManager.checkServerTrusted(chain, authType);
        } catch (CertificateException excep) {
        }
    }

    public X509Certificate[] getAcceptedIssuers() {
        return sunJSSEX509TrustManager.getAcceptedIssuers();
    }

}

        